import { createSelector } from '@ngrx/store';

import { MapState } from '../reducers';
import { getMapState } from './map.selector';
import { DistrictsState } from '../reducers/district.reducer';
import { District } from '../../../ngx-ol/models';

const getDistrictsState = createSelector(getMapState, (state: MapState) => state.districts);
const getDistrictsEntities = createSelector(getDistrictsState, (state: DistrictsState) => state.entities);
const getAllDistricts = createSelector(getDistrictsEntities, (entities: District[]) => entities);
const getDistrictsLoaded = createSelector(getDistrictsState, (state: DistrictsState) => state.loaded);
const getDistrictsLoading = createSelector(getDistrictsState, (state: DistrictsState) => state.loading);
const getDistrictsProvinces = createSelector(getDistrictsEntities, (entities: District[]) => {
    return entities.filter((district: District) => {
        if(Object.prototype.toString.call(district.citycode) === '[object Array]') {
            return true;
        }
    });
});
const getDistrictsHotcity = createSelector(getDistrictsEntities, (entities: District[]) => {
    let data: District[] = entities.filter((district: District) => {
        if(Object.prototype.toString.call(district.citycode) !== '[object Array]') {
            return true;
        }
    });
    data.unshift({
        citycode: [],
        adcode: '100000',
        name: '全国'
    });
    return data;
});

const getDistrictSelected = createSelector(
    getDistrictsState, 
    (state: DistrictsState) => state.selected
);

export const districtsSelector = {
    getDistrictsState,
    getDistrictsEntities,
    getAllDistricts,
    getDistrictsLoaded,
    getDistrictsLoading,
    getDistrictsProvinces,
    getDistrictsHotcity,
    getDistrictSelected
}